package net.openvision.util.parsing;

import java.io.IOException;
import java.io.Reader;
import java.util.BitSet;

import net.openvision.util.parsing.interfaces.Token;

public class DelimiterTokenReader extends TokenReader {

	private int linePosition;
	private Token currentDelimiter;
	private BitSet delimiters;
	private boolean ignoreWhitespace;
	
	public DelimiterTokenReader(Reader in, boolean ignoreWhitespace, char... delimiters) {
		super(in);
		this.ignoreWhitespace = ignoreWhitespace;
		this.delimiters = new BitSet(128);
		for (char c:delimiters) {
			this.delimiters.set(c);
		}
		currentDelimiter = null;
		linePosition = 0;
	}

	@Override
	public Token readToken() throws IOException {
		if (currentDelimiter != null) {
			Token result = currentDelimiter;
			currentDelimiter = null;
			return result;
		}
		StringBuilder sb = new StringBuilder();
		int lnr = getLineNumber();
		char ch = (char)read();
		while (ch >= 0) {
			if (Character.isWhitespace(ch) || delimiters.get(ch)) {
				if (!ignoreWhitespace || !Character.isWhitespace(ch))
					currentDelimiter = new TokenImpl(Character.toString(ch), getLineNumber(), linePosition);
				if (sb.length() > 0)
					return new TokenImpl(sb.toString(), getLineNumber(), linePosition-sb.length());
			} else {
				sb.append(ch);
			}
			ch = (char)read();
			linePosition++;
			if (lnr < getLineNumber()) {
				lnr = getLineNumber();
				linePosition = 0;
			}
		}
		return null;
	}

}
